import React, { useState } from 'react';
import {
    AutoComplete,
    Button,
    Cascader,
    Checkbox,
    Col,
    Form,
    Input,
    InputNumber,
    Row,
    Select,
    Card,
    message,
} from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

import { checkUserName, sendCaptcha, register } from '@/api/auth';

import './index.scss';
import { COLOR_THEME } from '@/config/theme';

const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 8,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};
function Register() {
    const [form] = Form.useForm();
    const [checkingUsername, setCheckingUsername] = useState(false);
    const [captchaCooldown, setCaptchaCooldown] = useState(0); // 倒计时剩余时间
    const [isSendingCaptcha, setIsSendingCaptcha] = useState(false); // 发送状态
    const [isSubmitting, setIsSubmitting] = useState(false);

    const navigate = useNavigate();

    const onFinish = async (values) => {
        try {
            setIsSubmitting(true);
            // 调用注册接口
            const response = await register({
                username: values.username,
                password: values.password,
                email: values.email,
                code: values.captcha,
            });

            if (response.code === 200) {
                message.success('注册成功，即将跳转登录页面');
                // 这里添加页面跳转逻辑，例如：
                navigate('/auth/login');
            } else {
                message.error(response.msg || '注册失败');
            }
        } catch (error) {
            console.error('注册请求异常:', error);
            message.error('网络请求异常，请稍后重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    const checkUsername = async (_, value) => {
        if (!value) return;
        setCheckingUsername(true);
        try {
            const isExist = await checkUserName({
                username: value,
            });
            console.log('查询结果', isExist);
            if (isExist.data) {
                return Promise.reject(new Error('用户名已存在'));
            }
            return Promise.resolve();
        } finally {
            setCheckingUsername(false);
        }
    };

    // 发送验证码处理函数
    const handleSendCaptcha = async () => {
        try {
            // 验证邮箱字段
            const email = form.getFieldValue('email');
            if (!email || !/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email)) {
                form.setFields([
                    {
                        name: 'email',
                        errors: ['请输入有效的邮箱地址'],
                    },
                ]);
                return;
            }

            setIsSendingCaptcha(true);
            // 调用发送验证码接口
            await sendCaptcha({ email: email });
            message.success('验证码已发送至您的邮箱');

            // 开始倒计时
            let countdown = 60;
            setCaptchaCooldown(countdown);
            const timer = setInterval(() => {
                countdown -= 1;
                setCaptchaCooldown(countdown);
                if (countdown <= 0) {
                    clearInterval(timer);
                }
            }, 1000);
        } catch (error) {
            console.error('发送验证码失败:', error);
        } finally {
            setIsSendingCaptcha(false);
        }
    };

    return (
        <div className="register">
            <Card
                className="register-card"
                style={{
                    backgroundColor: `${COLOR_THEME.QUATERNARY}50`,
                }}
            >
                <Form
                    {...formItemLayout}
                    form={form}
                    name="register"
                    onFinish={onFinish}
                    initialValues={{
                        residence: ['zhejiang', 'hangzhou', 'xihu'],
                        prefix: '86',
                    }}
                    style={{
                        maxWidth: 600,
                    }}
                    scrollToFirstError
                >
                    <Form.Item
                        name="username"
                        label="用户名"
                        validateFirst
                        validateTrigger="onBlur"
                        rules={[
                            {
                                required: true,
                                message: '请输入您的用户名!',
                                whitespace: true,
                            },
                            {
                                validator: checkUsername,
                            },
                        ]}
                    >
                        <Input
                            autoComplete="off"
                            suffix={checkingUsername ? <LoadingOutlined /> : null}
                            onPressEnter={(e) => e.preventDefault()} // 添加这行防止回车触发校验
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[
                            {
                                required: true,
                                message: '请输入您的密码!',
                            },
                            {
                                min: 8,
                                max: 12,
                                message: '密码长度需8-12位',
                            },
                            {
                                pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,12}$/,
                                message: '必须包含字母和数字',
                            },
                        ]}
                        hasFeedback
                    >
                        <Input.Password autoComplete="new-password" />
                    </Form.Item>

                    <Form.Item
                        name="confirm"
                        label="确认密码"
                        dependencies={['password']}
                        hasFeedback
                        rules={[
                            {
                                required: true,
                                message: '请再次输入您的密码!',
                            },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两个密码不一致!'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            {
                                type: 'email',
                                message: '邮箱输入格式有误!',
                            },
                            {
                                required: true,
                                message: '请输入您的邮箱!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item label="验证码">
                        <Row gutter={8}>
                            <Col span={12}>
                                <Form.Item
                                    name="captcha"
                                    noStyle
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入验证码!',
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Button onClick={handleSendCaptcha} disabled={captchaCooldown > 0 || isSendingCaptcha}>
                                    {isSendingCaptcha
                                        ? '发送中...'
                                        : captchaCooldown > 0
                                          ? `${captchaCooldown}秒后重试`
                                          : '发送验证码'}
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    {/* <Form.Item
            name="agreement"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
              },
            ]}
            {...tailFormItemLayout}
          >
            <Checkbox>
              I have read the <a href="">agreement</a>
            </Checkbox>
          </Form.Item> */}
                    <Form.Item {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit" loading={isSubmitting}>
                            {isSubmitting ? '注册中...' : '注 册'}
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
}
export default Register;
